package com.tiyo.system.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiyo.common.constant.Constants;
import com.tiyo.common.constant.UserConstants;
import com.tiyo.common.core.text.Convert;
import com.tiyo.common.exception.BusinessException;
import com.tiyo.common.utils.CacheUtils;
import com.tiyo.common.utils.StringUtils;
import com.tiyo.framework.shiro.util.ShiroUtils;
import com.tiyo.system.mapper.SysConfigMapper;
import com.tiyo.system.mapper.domain.SysConfig;
import com.tiyo.system.mapper.domain.SysUser;
import com.tiyo.system.service.SysConfigService;
@Service
public class SysConfigServiceImpl implements SysConfigService {
	@Autowired
	SysConfigMapper sysConfigMapper;
	  /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
    	QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<SysConfig>();
        List<SysConfig> configsList = sysConfigMapper.selectList(queryWrapper);
        for (SysConfig config : configsList)
        {
            CacheUtils.put(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }
	@Override
	public SysConfig selectConfigById(String configId) {
		return sysConfigMapper.selectById(configId);
	}

	@Override
	public String selectConfigByKey(String configKey) {
		 String configValue = Convert.toStr(CacheUtils.get(getCacheName(), getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<SysConfig>();
        queryWrapper.eq("config_key", configKey);
		SysConfig config= sysConfigMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(config))
        {
            CacheUtils.put(getCacheName(), getCacheKey(configKey), config.getConfigValue());
            return config.getConfigValue();
        }
        return StringUtils.EMPTY;
	}

    @Override
	public void insertConfig(SysConfig config) {
    	Date current = new Date();
    	SysUser user= ShiroUtils.getSysUser();
    	config.setCreateUserId(user.getUserId());
    	config.setCreateUserName(user.getUserName());
    	config.setCreateDate(current);
    	sysConfigMapper.insert(config);
		
	}
	@Override
	public void updateConfig(SysConfig config) {
		Date current = new Date();
    	SysUser user= ShiroUtils.getSysUser();
    	config.setModifyUserId(user.getUserId());
    	config.setModifyUserName(user.getUserName());
    	config.setModifyDate(current);
    	int row = sysConfigMapper.updateById(config);
        if (row > 0)
        {
            CacheUtils.put(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
	}
	
	@Override
	public IPage<SysConfig> page(SysConfig pageParams) {
		Page<SysConfig> ipage = new Page<SysConfig>(1, 10);
		QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<SysConfig>();
		return sysConfigMapper.selectPage(ipage, queryWrapper);
	}
	@Override
	public void deleteConfigByIds(String ids) {
		String[] configIds = Convert.toStrArray(ids, ",");
        for (String configId : configIds)
        {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
            {
                throw new BusinessException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
        }
		int count = sysConfigMapper.deleteBatchIds(Arrays.asList(configIds));
		if (count > 0) {
			CacheUtils.removeAll(getCacheName());
		}
		
	}
	@Override
	public String checkConfigKeyUnique(SysConfig config) {
		 QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<SysConfig>();
		queryWrapper.eq("config_key", config.getConfigKey());
		SysConfig info= sysConfigMapper.selectOne(queryWrapper);
		if(StringUtils.isNotNull(info)&&!info.getConfigId().equals(config.getConfigId())) {
            return UserConstants.CONFIG_KEY_NOT_UNIQUE;
        }
        return UserConstants.CONFIG_KEY_UNIQUE;
	}
	/**
     * 清空缓存数据
     */
    @Override
    public void clearCache()
    {
        CacheUtils.removeAll(getCacheName());
    }
	   /**
     * 获取cache name
     * 
     * @return 缓存名
     */
    private String getCacheName()
    {
        return Constants.SYS_CONFIG_CACHE;
    }
    /**
     * 设置cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return Constants.SYS_CONFIG_KEY + configKey;
    }
}
